package com.qf.reliability;

import com.qf.util.MQConnUtil;
import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.ConfirmListener;
import com.rabbitmq.client.Connection;
import org.junit.Test;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class ConfirmPublisher {

    @Test
    public void publish() throws Exception, TimeoutException {
        //1. 获取连接对象Conn
        Connection conn = MQConnUtil.getConn();
        //2. 获取管道对象Channel
        Channel channel = conn.createChannel();
        //3. 声明Exchange
        channel.exchangeDeclare("confirm_exchange", BuiltinExchangeType.TOPIC);
        //4. 声明Queue
        channel.queueDeclare("confirm_queue",true,false,false,null);
        //5. 绑定Exchange和Queue
        channel.queueBind("confirm_queue","confirm_exchange","confirm.#");
        String msg = "我是一个消息!!!";
        //------------------------------------------------------------------------
        //6. 开启Confirm机制
        channel.confirmSelect();
        //7. 配置Confirm的异步回调
        channel.addConfirmListener(new ConfirmListener() {
            @Override
            public void handleAck(long deliveryTag, boolean multiple) throws IOException {
                System.out.println(msg + "发送成功!!");
            }

            @Override
            public void handleNack(long deliveryTag, boolean multiple) throws IOException {
                System.out.println(msg + "发送失败,保存到数据库,后期让客服,运维人员进行二次处理.");
            }
        });
        //------------------------------------------------------------------------
        //8. 发送消息
        channel.basicPublish("confirm_exchange","confirm.xxxxxxxx",null,msg.getBytes());
        System.out.println("消息成功发送!");
        //9. System.in.read();
        System.in.read();
        //10. 释放资源
        channel.close();
        conn.close();

    }


}
